package cn.cms.controller;

import cn.cms.model.SysMenu;
import cn.cms.model.SysRole;
import cn.cms.model.SysUser;
import cn.cms.service.SysMenuService;
import cn.cms.service.SysRoleService;
import cn.cms.service.SysUserService;
import cn.cms.util.SessionUtil;
import cn.cms.util.StringUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping(value = "/index")
public class IndexController {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    SysMenuService sysMenuService;

    @RequestMapping
    public String index(HttpServletRequest request, Model model) {
        List<String> roleIds = new ArrayList<>();
        SysUser loginUser = SessionUtil.getUserSession(request);
        loginUser = sysUserService.get(loginUser.getId());
        roleIds.addAll(Arrays.asList(((loginUser.getRoleIds() == null) ? "" : loginUser.getRoleIds()).split(",")));

        Set<String> menuIds = new HashSet<>();
        StringBuilder roleDetail = new StringBuilder();
        roleIds.forEach(k -> {
            if (!StringUtil.isSpaceOrNull(k)) {
                SysRole sysRole = sysRoleService.getRoleById(Integer.valueOf(k));
                roleDetail.append(sysRole.getRoleName()).append(",");
                menuIds.addAll(Arrays.asList(sysRole.getMenuIds().split(",")));
            }
        });

        if (roleDetail.length() > 0) {
            loginUser.setRoleDetail(roleDetail.substring(0, roleDetail.length() - 1));
        }

        List<SysMenu> sysMenus = sysMenuService.getMenus(menuIds);
        System.out.println(JSON.toJSON(sysMenus));
        model.addAttribute("sysMenus", JSON.toJSON(sysMenus));

        model.addAttribute("roleDetail", loginUser.getRoleDetail());

        return "index/index";
    }

    @RequestMapping(value = "/usual")
    public String usual() {
        return "index/usual";
    }

/*    @RequestMapping(value = "getCategory")
    @ResponseBody
    public String getCategory(@RequestParam("id") int id) {

        Map<String, String> category = Constants.SECOND_CATEGORY.get(id);
        return JSON.toJSONString(category);
    }*/
}
